package com.shwread.android.ui.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.shwread.android.qysw.activity.BaseBusinessActivity;
import com.shwread.android.qysw10000136.R;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.shwread.httpsdk.http.face.AddCommentAction;
import logic.constants.DefaultConsts;
import logic.util.Util;
import logic.util.Utils;


/**
 * 底部评论
 * 
 * @author 刘宾
 * @date 2015年2月2日 下午2:37:24
 */
public class CommentView
        extends
        LinearLayout
        implements
        OnClickListener
{
	private ImageView            ivEmoji;
	private EditText             etContent;
	private Button               submitBtn;
	private Context              mContext;
	private String               btnString = "发送";
	/** true:评论，false:回复 */
	private boolean              isComment;
	private BaseBusinessActivity activity;
	
	private String               targetType;       //评论的内容类型
	private String               targetValue;      //评论的内容值
	private String               content;          //评论内容
	private Long                 targetUserId;     //被回复的目标对象的用户id
	private String               targetUserAccount; //被回复的目标对象的用户账号
	private Long                 commentId;        //被回复的评论记录记录id
	private boolean              isBack=false;
	                                                
	public CommentView(Context context) {
		super(context);
		initView(context);
	}
	
	public CommentView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView(context);
	}
	
	@SuppressLint ("NewApi")
	public CommentView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initView(context);
	}
	
	private void initView(Context context) {
		mContext = context;
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		RelativeLayout containerView = (RelativeLayout) LayoutInflater.from(context).inflate(R.layout.comment_view, null);
		ivEmoji = (ImageView) containerView.findViewById(R.id.comment_view_emoji);
		etContent = (EditText) containerView.findViewById(R.id.comment_view_content);
		submitBtn = (Button) containerView.findViewById(R.id.comment_view_commit);
		
		submitBtn.setText(btnString);
		setDefaultHint();
		
		etContent.addTextChangedListener(new TextChanged());
		etContent.setOnFocusChangeListener(new FocusChange());
		ivEmoji.setOnClickListener(this);
		submitBtn.setOnClickListener(this);
		addView(containerView, lp);
	}
	
	/** 设置自定义提示语 */
	public void setHintString(String nickName) {
		if (null == etContent || Util.isEmpty(nickName)) return;
		etContent.setHint(String.format("回复%s:", nickName));
	}
	
	/** 设置默认的提示语 */
	public void setDefaultHint() {
		if (null == etContent) return;
		etContent.setHint("说说你的看法吧");
	}
	
	/** 设置右侧按钮显示的文字 */
	public void setButtonString(String str) {
		if (null == etContent || Util.isEmpty(str)) return;
		btnString = str;
		etContent.setText(str);
	}
	
	/** 设置取消 */
	public void setButtonBack(boolean b) {
		isBack=b;
		if (isBack) {
			enabledBtn(true);
			submitBtn.setText("取消");
		}

	}
	
	/** 隐藏输入法 */
	public void hideInputMethod() {
		if (null == etContent || null == mContext) return;
		Util.hideInputMethodManager(mContext, etContent);
	}
	
	/** 显示输入法 */
	public void showInputMethod() {
		if (null == etContent || null == mContext) return;
		Util.showInputMethodManager(mContext);
		etContent.setFocusable(true);
		etContent.setFocusableInTouchMode(true);
		etContent.requestFocus();
	}
	
	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
			case R.id.comment_view_emoji:
				//TODO
				Util.showToast(mContext, "点击表情");
				break;
			case R.id.comment_view_commit:
				if (isBack) {
					if (submitBtn.getText().equals("取消")) {
						//隐藏输入法
						Util.hideInputMethodManager(mContext, arg0);
						Message msg = new Message();
						msg.what = DefaultConsts.COMMENT_SUBMIT_BACK;
						activity.getUIHandler().sendMessage(msg);
					}
					else if (submitBtn.getText().equals("发送")) {
						commit();	
					}
				}
				else {
					commit();					
				}
				break;
		}
	}
	
	/** 发表评论 */
	private void commit() {
		if (null == etContent) return;
		if (etContent.getText().toString().length() > 140)
		{
			activity.getUIHandler().post(new Runnable()
			{
				
				@Override
				public void run() {
					Utils.showToast(activity, "不能超过140字");
				}
			});
		}
		else
		{
			content = etContent.getText().toString().trim();
			if (Util.isNotEmpty(content))
			{
				if (isComment)
				{
					if (checkNull(targetType, targetValue, content))
					{
						enabledBtn(false);
						new AddCommentAction(mContext, targetType, targetValue, content, null, null, null, new CommentListener()).start();
					}
				}
				else
				{
					if (checkNull(targetType, targetValue, content, targetUserId, targetUserAccount, commentId))
					{
						enabledBtn(false);
						new AddCommentAction(mContext, targetType, targetValue, content, targetUserId, targetUserAccount, commentId, new CommentListener()).start();
					}
				}
			}
		}
	}
	
	private class CommentListener
	        implements
	        ActionListener
	{
		@Override
		public void OK(Object obj) {
			if (null == activity) return;
			activity.getUIHandler().post(new Runnable()
			{
				@Override
				public void run() {
					if (null != activity)
					{
						Message msg = new Message();
						msg.what = DefaultConsts.COMMENT_SUBMIT_SUCCESS;
						msg.obj = content;
						activity.getUIHandler().sendMessage(msg);
					}
					etContent.setText("");
					content = "";
					//TODO
					Util.showToast(mContext, "评论成功");
					hideInputMethod();
				}
			});
		}
		
		@Override
		public void ERROR(int resultCode, final String message) {
			if (null == activity) return;
			activity.getUIHandler().post(new Runnable()
			{
				@Override
				public void run() {
					Util.showToast(mContext, message);
					enabledBtn(true);
					if (null != activity)
					{
						activity.getUIHandler().sendEmptyMessage(DefaultConsts.COMMENT_SUBMIT_ERROR);
					}
				}
			});
		}
		
		@Override
		public void HTTPERROR(int statusCode) {
			if (null == activity) return;
			activity.getUIHandler().post(new Runnable()
			{
				@Override
				public void run() {
					Util.showToast(mContext, "网络连接超时");
					enabledBtn(true);
					if (null != activity)
					{
						activity.getUIHandler().sendEmptyMessage(DefaultConsts.COMMENT_SUBMIT_ERROR);
					}
				}
			});
		}
	}
	
	private class TextChanged
	        implements
	        TextWatcher
	{
		
		@Override
		public void afterTextChanged(Editable arg0) {
		}
		
		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		}
		
		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			if (isBack) {
				enabledBtn(true);
				if (Util.isNotEmpty(arg0.toString())) {
					submitBtn.setText("发送");
				}
				else {
					submitBtn.setText("取消");
				}
			}
			else {
				enabledBtn(Util.isNotEmpty(arg0.toString()));
			}
		}
	}
	
	private void enabledBtn(boolean value) {
		if (null == submitBtn || null == mContext) return;
		submitBtn.setTextColor(mContext.getResources().getColor(value ? R.color.comment_tv_color_enable : R.color.comment_tv_color));
		submitBtn.setEnabled(value);
	}
	
	private class FocusChange
	        implements
	        OnFocusChangeListener
	{
		@Override
		public void onFocusChange(View arg0, boolean arg1) {
			if (null == submitBtn || null == mContext) return;
			if (arg1)
			{
				//				ivEmoji.setVisibility(View.VISIBLE);
				submitBtn.setVisibility(View.VISIBLE);
			}
			else
			{
				//				ivEmoji.setVisibility(View.GONE);
				submitBtn.setVisibility(View.GONE);
				//隐藏输入法
				Util.hideInputMethodManager(mContext, arg0);
			}
		}
	}
	
	/**
	 * 设置回复评论的参数
	 * 
	 * @param targetType
	 *            评论的内容类型
	 * 
	 *            <pre>
	 * 1=书籍 
	 * 2=专区内容(资讯、视音频等类型) 
	 * 3=图集图片 
	 * 4=图集 
	 * 5=考试系统 
	 * 6=互动中心
	 * </pre>
	 * @param targetValue
	 *            评论的内容值
	 * 
	 *            <pre>
	 * 如果targetType为1，则为书籍id;
	 * 如果targetType为2，则为对应的内容详细id;
	 * 如果targetType为3；则为图片id;
	 * 如果targetType为4，则为图集栏目id;
	 * 如果targetType为5，则为考试课程id;
	 * 如果targetType为6，则为主题id;
	 * </pre>
	 * @param targetUserId
	 *            <选填>被回复的目标对象的用户id
	 * @param targetUserAccount
	 *            <选填>被回复的目标对象的用户账号
	 * @param commentId
	 *            <选填>被回复的评论记录记录id
	 */
	public void setReplyParams(BaseBusinessActivity activity, String targetType, String targetValue, Long targetUserId, String targetUserAccount, Long commentId) {
		isComment = false;
		this.activity = activity;
		this.targetType = targetType;
		this.targetValue = targetValue;
		this.targetUserId = targetUserId;
		this.targetUserAccount = targetUserAccount;
		this.commentId = commentId;
	}
	
	/**
	 * 设置评论的参数
	 * 
	 * @param targetType
	 *            评论的内容类型
	 * 
	 *            <pre>
	 * 1=书籍 
	 * 2=专区内容(资讯、视音频等类型) 
	 * 3=图集图片 
	 * 4=图集 
	 * 5=考试系统 
	 * 6=互动中心
	 * </pre>
	 * @param targetValue
	 *            评论的内容值
	 * 
	 *            <pre>
	 * 如果targetType为1，则为书籍id;
	 * 如果targetType为2，则为对应的内容详细id;
	 * 如果targetType为3；则为图片id;
	 * 如果targetType为4，则为图集栏目id;
	 * 如果targetType为5，则为考试课程id;
	 * 如果targetType为6，则为主题id;
	 * </pre>
	 */
	public void setCommentParams(BaseBusinessActivity activity, String targetType, String targetValue) {
		isComment = true;
		this.activity = activity;
		this.targetType = targetType;
		this.targetValue = targetValue;
	}
	
	private boolean checkNull(Object... params) {
		for (Object object : params)
		{
			if (null == object || Util.isEmpty(object.toString()))
			{
				//TODO
				Util.showToast(mContext, "必填参数为空");
				enabledBtn(true);
				return false;
			}
		}
		return true;
	}
}
